package xiaojian.toolkit.netty.handler.callback;

import com.google.common.cache.Cache;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.apache.commons.collections4.Closure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.util.IdentifyableOfInt;

public class IntIdCallbackResponseHandler<I extends IdentifyableOfInt> extends
		ChannelInboundHandlerAdapter {
	private static Logger logger = LoggerFactory
			.getLogger(IntIdCallbackResponseHandler.class);

	private Cache<Integer, Closure> uuidCache;

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("hey,channelActive");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("channelInactive");
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		logger.warn("", cause);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		logger.debug("message received : {}", msg);
		int uuid = ((I) msg).getIntIdentification();
		Closure closure = uuidCache.getIfPresent(uuid);
		if (closure != null) {
			closure.execute(msg);
			uuidCache.invalidate(uuid);
		} else {
			logger.warn("can't find matched uuid {}", uuid);
		}
	}

	public void setUuidCache(Cache<Integer, Closure> uuidCache) {
		this.uuidCache = uuidCache;
	}
}
